#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    yy=new Thread;
    yy->start();//启动线程
    yy->stopped=1;//初始化变量
    yy->write_rs=0;
    yy->read_rs=0;

/*******************************************************************************************/
    timer = new QTimer(this);                                   //定时读数据
    timer->start(100);                                          //定时读数据
    connect(timer,SIGNAL(timeout()),this,SLOT(readThread()));   //定时读数据
/*******************************************************************************************/
    connect(ui->writeButton,SIGNAL(clicked()),this,SLOT(writeThread()));    //信号与槽
//    connect(ui->readButton,SIGNAL(clicked()),this,SLOT(readThread()));    //按键读数据
/*******************************************************************************************/
    connect(ui->closeButton,SIGNAL(clicked()),this,SLOT(closeThread()));    //按键关闭线程
/*******************************************************************************************/
//    connect(ui->writeButton,&QPushButton::clicked,this,SLOT(writeThread()));  //QT5不适用
//    connect(ui->readButton,&QPushButton::clicked,this,SLOT(readThread()));    //QT5不适用
//    connect(ui->closeButton,&QPushButton::clicked,this,SLOT(closeThread()));  //QT5不适用
    connect(yy,SIGNAL(finished()),this,SLOT(display()));//前面线程读完了不是发一个信号么，这个信号就是发到这个槽
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::display()
{
    ui->dis_label->setText(yy->buf);//读到的在dis_label显示，dis_label就是我们前面designer放的标签
    char *m_pData;
    QString temp;
//    char p[]={2,4,6,8};//测试使用
    m_pData=yy->buf;
    for (int i=0;i<77;i++)
    {
        QString s;
//        s.sprintf("0x%02x, ",(unsigned char)*m_pData);
        s.sprintf("%02x, ",(unsigned char)*m_pData);
        temp +=s;
//        ui->textEdit->append(s);
        m_pData=m_pData+1;
        s.clear();
    }
    ui->textEdit->append(temp);
    temp.clear();
}

void MainWindow::writeThread()  //前面线程都是根据stopped、write、read_rs的状态来工作的
{
    yy->write_rs=1;
}

void MainWindow::readThread()
{
    yy->read_rs=1;
}

void MainWindow::closeThread()
{
    yy->stopped=0;
    timer->stop();//有用定时器是要关闭
}
